/**
 * 日志系统
 */
import * as vscode from 'vscode';
import { LogLevel } from './types';

/**
 * 日志管理器类
 */
export class Logger {
    private static instance: Logger;
    private readonly outputChannel: vscode.OutputChannel;
    private debugEnabled: boolean = false;

    private constructor() {
        this.outputChannel = vscode.window.createOutputChannel('PHP Zero Reference Highlighter');
    }

    /**
     * 获取日志管理器实例
     */
    public static getInstance(): Logger {
        if (!Logger.instance) {
            Logger.instance = new Logger();
        }
        return Logger.instance;
    }

    /**
     * 设置调试模式
     */
    public setDebugEnabled(enabled: boolean): void {
        this.debugEnabled = enabled;
    }

    /**
     * 记录调试信息
     */
    public debug(message: string, ...args: any[]): void {
        if (this.debugEnabled) {
            this.log(LogLevel.DEBUG, message, ...args);
        }
    }

    /**
     * 记录信息
     */
    public info(message: string, ...args: any[]): void {
        this.log(LogLevel.INFO, message, ...args);
    }

    /**
     * 记录警告
     */
    public warn(message: string, ...args: any[]): void {
        this.log(LogLevel.WARN, message, ...args);
        console.warn(`[PHP Zero Ref] ${message}`, ...args);
    }

    /**
     * 记录错误
     */
    public error(message: string, error?: Error, ...args: any[]): void {
        const errorMessage = error ? `${message}: ${error.message}` : message;
        this.log(LogLevel.ERROR, errorMessage, ...args);
        console.error(`[PHP Zero Ref] ${errorMessage}`, error, ...args);
    }

    /**
     * 显示输出面板
     */
    public show(): void {
        this.outputChannel.show();
    }

    /**
     * 清空日志
     */
    public clear(): void {
        this.outputChannel.clear();
    }

    /**
     * 释放资源
     */
    public dispose(): void {
        this.outputChannel.dispose();
    }

    /**
     * 内部日志方法
     */
    private log(level: LogLevel, message: string, ...args: any[]): void {
        const timestamp = new Date().toISOString();
        const formattedMessage = `[${timestamp}] [${level}] ${message}`;

        this.outputChannel.appendLine(formattedMessage);

        if (args.length > 0) {
            this.outputChannel.appendLine(`Arguments: ${JSON.stringify(args, null, 2)}`);
        }

        // 在调试模式下也输出到控制台
        if (this.debugEnabled) {
            console.log(`[PHP Zero Ref] ${formattedMessage}`, ...args);
        }
    }
}